package com.example.myapplication.extensions

import android.app.Activity
import android.content.Context
import androidx.appcompat.app.AlertDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

fun Long.formatDuration(): String {
    val totalSeconds = this / 1000
    val hours = totalSeconds / 3600
    val remainingSeconds = totalSeconds % 3600
    val minutes = remainingSeconds / 60
    val seconds = remainingSeconds % 60
    return if (hours > 0) {
        "%02d:%02d:%02d".format(hours, minutes, seconds)
    } else {
        "%02d:%02d".format(minutes, seconds)
    }
}

fun <T> CoroutineScope.runOnBackgroundThenUi(
    backgroundTask: suspend () -> T,
    uiAction: suspend (T) -> Unit
) {
    launch(Dispatchers.IO) {
        val result = backgroundTask()
        withContext(Dispatchers.Main) { uiAction(result) }
    }
}

fun Activity.showNormalDialog(context: Context, title: String?, content: String, onConfirm: () -> Unit) {
    AlertDialog.Builder(context)
        .setTitle(title ?: "提示")
        .setMessage(content)
        .setNegativeButton("取消") { dialog, _ -> dialog.dismiss() }
        .setPositiveButton("确定") { _, _ -> onConfirm() }
        .create()
        .show()
}